import { calculateOrder } from "../../api/api";

// components/product-detail/product-detail.js
Component({
  properties: {
    // 组件接收的外部属性
    product: {
      type: Object,
      value: {}
    },
    configPrice:{
      type: Array,
      value: []
    }
  },
  lifetimes: {
    attached() {
      // 创建时执行
      console.log(this.product)
    }
  },
  attached(){
  },
  data: {
    total: 0
  },
  mouthed() {
    // 组件初始化时执行
  },
  methods: {
    onChange(e){
      const product = this.properties.product
      const index = e.currentTarget.dataset.index
      if(e.detail.value){
        product.specifications[index].selected = e.detail.value
      }
      console.log(product)
      this.setData({
        product: product
      })

      const _this = this
      setTimeout(() => {
        _this.handleCalculate()
      })
    },
    handleRemove(){
      const product = this.properties.product
      if(product.count <= 1){
        return
      }
      product.count--
      this.setData({
        product: product
      })
      const _this = this
      setTimeout(() => {
        _this.handleCalculate()
      })
    },
    handleAdd(){
      const product = this.properties.product
      product.count++
      this.setData({
        product: product
      })
      const _this = this
      setTimeout(() => {
        _this.handleCalculate()
      })
    },
    handleClose(){
      this.triggerEvent('close')
    },
    addToCart() {
      const product = this.properties.product
      this.triggerEvent('addToCart', product)
    },


  /** 计算订单  */
  handleCalculate() {
    // 处理支付逻辑
    const commodityList = []
    const specifications = {}
    this.properties.product.specifications.forEach(item => {
      specifications[item.name] = item.selected
    })
    const obj = {
      id: this.properties.product.id,
      name: this.properties.product.name,
      amount: this.properties.product.count,
      specifications: JSON.stringify(specifications)
    }

    commodityList.push(obj)
    calculateOrder({
      voucherId: 0,
      commodityList
    }).then(r => {
      this.setData({
        total: r.data.actualPrice,
      })
    })
  },
  },
});
